<?php


namespace Lenntc\Framework\Exception\Handler;


use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Lenntc\Framework\Constants\ErrorCode;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ValidationExceptionHandler extends ExceptionHandler
{

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->stopPropagation();

        /**
         * @var ValidationException $throwable
         */
        $falseMessage = $throwable->validator->errors()->first();

        $data = ['code'=>ErrorCode::INVALID_PARAM, 'msg'=>$falseMessage,'data'=>[],'time'=>time()];
        $dataStream = new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE));

        return $response->withAddedHeader('Content-Type', 'application/json;charset=utf-8')
            ->withStatus($throwable->status)
            ->withBody($dataStream);

    }

    public function isValid(Throwable $throwable): bool
    {
        $validateException = ValidationException::class;
        if(class_exists($validateException) && $throwable instanceof $validateException){
            return true;
        }
        return false;
    }

}